package com.ln.prac.lianglianglee.jmx;

import java.lang.management.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * 获取当前JVM的MXBean信息
 *
 * @Author zhangj
 * @Date 2023/2/13 21:36
 */
public class MXBeanTest {

    private static final Logger logger = Logger.getLogger(MXBeanTest.class.getName());

    public static void main(String[] args) {
        Map<String, Object> beanMap = loadMXBeanMap();
        beanMap.forEach((k, v) -> {
            logger.info(k);
            if (v instanceof Collection) {
                ((Collection) v).stream().forEach(vv -> {
                    logger.info(v.toString());
                });
            } else {
                logger.info(v.toString());
            }
            System.out.println();
        });
    }

    private static Map<String, Object> loadMXBeanMap() {
        // 操作系统信息
        OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        // 运行时
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        // JVM 内存信息
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        // JVM 内存池 - 列表
        List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
        // 内存管理器 - 列表
        List<MemoryManagerMXBean> memoryManagerMXBeans = ManagementFactory.getMemoryManagerMXBeans();
        // class 加载统计信息
        ClassLoadingMXBean classLoadingMXBean = ManagementFactory.getClassLoadingMXBean();
        // 编译统计信息
        CompilationMXBean compilationMXBean = ManagementFactory.getCompilationMXBean();
        // 线程
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        // GC
        List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
        // 获取平台日志 MXBean
        PlatformLoggingMXBean platformLoggingMXBean = ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class);

        Map<String, Object> beansMap = new HashMap<>();
        beansMap.put("operatingSystemMXBean", operatingSystemMXBean);
        beansMap.put("runtimeMXBean", runtimeMXBean);
        beansMap.put("memoryMXBean", memoryMXBean);
        beansMap.put("memoryPoolMXBeans", memoryPoolMXBeans);
        beansMap.put("memoryManagerMXBeans", memoryManagerMXBeans);
        beansMap.put("classLoadingMXBean", classLoadingMXBean);
        beansMap.put("compilationMXBean", compilationMXBean);
        beansMap.put("threadMXBean", threadMXBean);
        beansMap.put("garbageCollectorMXBeans", garbageCollectorMXBeans);
        beansMap.put("platformLoggingMXBean", platformLoggingMXBean);
        return beansMap;
    }

}
